package org.bbs.demo.reply.api;

import org.bbs.demo.advice.BusinessException;
import org.bbs.demo.common.BBSConstants;
import org.bbs.demo.common.Result;
import org.bbs.demo.reply.dao.LikeDao;
import org.bbs.demo.reply.dto.UserRReplyLikeDto;
import org.bbs.demo.utils.jwtutil.JWTutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/comment")
@Transactional //事务声明，表示该类的所有方法都是事务性的，即方法中的所有访问数据库操作构成了一个整体事务，具有原子性
public class StoreyLikeApi {
    @Autowired
    private LikeDao likedao;

    @PostMapping("/storeyReply/like")
    public Result info(@RequestBody UserRReplyLikeDto userrreplylikedto, @RequestHeader String Token){
        try{

            String userId = JWTutil.getUserID(Token);
            userrreplylikedto.setUser_id(userId);
            if(likedao.findStoreyRid(userrreplylikedto.getStorey_r_id()) == null){
                throw new BusinessException("回复id不存在");
                //return Result.err(BBSConstants.CODE_ERR_BUSINESS,"回复id不存在");
            }
            if(likedao.findURRLikes(userrreplylikedto) == null){
                likedao.addURRLikes(userrreplylikedto);
                likedao.addStoreyRLikes(userrreplylikedto.getStorey_r_id());
                return Result.OK("点赞成功");
            }
            else{
                likedao.deleteURRLikes(userrreplylikedto);
                likedao.subStoreyRLikes(userrreplylikedto.getStorey_r_id());
                return Result.OK("取消点赞成功");
            }

        }catch (DuplicateKeyException err) {
            throw new BusinessException("点赞失败");
            //return Result.err(BBSConstants.CODE_ERR_SYS, "评论失败");
        }
    }
}
